package com.qyhl.module_practice.rank.person;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeIsVolunteerBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeVolunteerBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeVolunteerDetailBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


@Route(path = ARouterPathConstant.PRACTICE_SCORE_RANK)
public class PracticeScoreRankActivity extends BaseActivity implements PracticeScoreRankContract.PracticeScoreRankView {
    @BindView(R2.id.back_btn)
    TextView backBtn;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    LinearLayout tipLayout, valueLayout;
    RoundedImageView headIcon;
    TextView name;
    TextView rankNum;
    TextView actNum;
    TextView actTime;
    TextView scoreNum;

    private PracticeScoreRankPresenter mPresenter;

    private HeaderAndFooterWrapper<PracticeVolunteerBean> headerAndFooterWrapper;

    private int volId;

    private int type;  //1 时长   2 次数   3 积分

    private List<PracticeVolunteerBean> mDataList = new ArrayList<>();

    private int page = 1;

    private String username;

    private String instId;


    private enum Status {
        NOT_LOGIN,  //未登录
        NOT_VOL,  //非志愿者
        VOL_JUDGE, //志愿者审核中
        NORMAL, //志愿者
        ERROR,   //获取失败
        ERROR1
    }

    private Status status = Status.NOT_LOGIN;

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_score_rank;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.fullScreen(true).statusBarDarkFont(false).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        username = CommonUtils.getInstance().getUserName();
        BusFactory.getBus().register(this);
        mPresenter = new PracticeScoreRankPresenter(this);
        volId = getIntent().getIntExtra("id", 0);
        type = getIntent().getIntExtra("type", 1);
        instId = getIntent().getStringExtra("instId");
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        View headView = LayoutInflater.from(this).inflate(R.layout.practice_item_rank_header, null);
        headIcon = (RoundedImageView) headView.findViewById(R.id.head_icon);
        name = (TextView) headView.findViewById(R.id.name);
        rankNum = (TextView) headView.findViewById(R.id.rank_num);
        actNum = (TextView) headView.findViewById(R.id.act_num);
        actTime = (TextView) headView.findViewById(R.id.act_time);
        scoreNum = (TextView) headView.findViewById(R.id.score_num);
        tipLayout = (LinearLayout) headView.findViewById(R.id.tip_layout);
        valueLayout = headView.findViewById(R.id.value_layout);
        switch (type) {
            case 1:
                backBtn.setText("志愿者服务时长排行");
                break;
            case 2:
                backBtn.setText("志愿者服务项目排行");
                break;
            case 3:
                backBtn.setText("志愿者服务积分排行");
                break;
        }

        recycleView.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.practice_item_news_divider));
        recycleView.addItemDecoration(divider);

        headerAndFooterWrapper = new HeaderAndFooterWrapper<>(new CommonAdapter<PracticeVolunteerBean>(this, R.layout.practice_item_rank, mDataList) {
            @Override
            protected void convert(ViewHolder holder, PracticeVolunteerBean bean, int position) {
                holder.setText(R.id.name, bean.getName());

                switch (type) {
                    case 1:
                        holder.setText(R.id.value_num, DateUtils.PracticeServiceTimeFormat(bean.getServiceTimes()));
                        break;
                    case 2:
                        holder.setText(R.id.value_num, bean.getServiceNums() + "");
                        break;
                    case 3:
                        holder.setText(R.id.value_num, bean.getTotalScore() + "");
                        break;
                }

                RoundedImageView head = holder.getView(R.id.head_icon);
                Glide.with(PracticeScoreRankActivity.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                        .into(head);

                switch (position - 1) {
                    case 0:
                        holder.setVisible(R.id.head_tag, true);
                        holder.setVisible(R.id.rank_num, false);
                        holder.setVisible(R.id.rank_num_tag, true);

                        holder.setImageResource(R.id.rank_num_tag, R.drawable.practice_rank_no1_icon);
                        holder.setImageResource(R.id.head_tag, R.drawable.practice_rank_head_one_icon);
                        if (bean.getId() == volId) {
                            holder.setTextColorRes(R.id.value_num, R.color.global_base);
                            holder.setVisible(R.id.myself_tag, true);
                            holder.setTextColorRes(R.id.name, R.color.global_base);
                        } else {
                            holder.setTextColorRes(R.id.value_num, R.color.global_black_lv1);
                            holder.setVisible(R.id.myself_tag, false);
                            holder.setTextColorRes(R.id.name, R.color.global_black_lv1);
                        }
                        break;
                    case 1:
                        holder.setVisible(R.id.head_tag, true);
                        holder.setVisible(R.id.rank_num, false);
                        holder.setVisible(R.id.rank_num_tag, true);

                        holder.setImageResource(R.id.rank_num_tag, R.drawable.practice_rank_no2_icon);
                        holder.setImageResource(R.id.head_tag, R.drawable.practice_rank_head_two_icon);
                        if (bean.getId() == volId) {
                            holder.setTextColorRes(R.id.value_num, R.color.global_base);
                            holder.setVisible(R.id.myself_tag, true);
                            holder.setTextColorRes(R.id.name, R.color.global_base);
                        } else {
                            holder.setTextColorRes(R.id.value_num, R.color.global_black_lv1);
                            holder.setVisible(R.id.myself_tag, false);
                            holder.setTextColorRes(R.id.name, R.color.global_black_lv1);
                        }
                        break;
                    case 2:
                        holder.setVisible(R.id.head_tag, true);
                        holder.setVisible(R.id.rank_num, false);
                        holder.setVisible(R.id.rank_num_tag, true);

                        holder.setImageResource(R.id.rank_num_tag, R.drawable.practice_rank_no3_icon);
                        holder.setImageResource(R.id.head_tag, R.drawable.practice_rank_head_three_icon);
                        if (bean.getId() == volId) {
                            holder.setTextColorRes(R.id.value_num, R.color.global_base);
                            holder.setVisible(R.id.myself_tag, true);
                            holder.setTextColorRes(R.id.name, R.color.global_base);
                        } else {
                            holder.setTextColorRes(R.id.value_num, R.color.global_black_lv1);
                            holder.setVisible(R.id.myself_tag, false);
                            holder.setTextColorRes(R.id.name, R.color.global_black_lv1);
                        }
                        break;
                    default:
                        holder.setVisible(R.id.head_tag, false);
                        holder.setVisible(R.id.rank_num, true);
                        holder.setVisible(R.id.rank_num_tag, false);

                        if (bean.getId() == volId) {
                            holder.setTextColorRes(R.id.value_num, R.color.global_base);
                            holder.setVisible(R.id.myself_tag, true);
                            holder.setTextColorRes(R.id.name, R.color.global_base);
                            holder.setTextColorRes(R.id.rank_num, R.color.global_base);
                        } else {
                            holder.setTextColorRes(R.id.value_num, R.color.global_black_lv1);
                            holder.setVisible(R.id.myself_tag, false);
                            holder.setTextColorRes(R.id.name, R.color.global_black_lv1);
                            holder.setTextColorRes(R.id.rank_num, R.color.global_black_lv1);
                        }

                        holder.setText(R.id.rank_num, "No." + position);
                        break;
                }
            }
        });


        headerAndFooterWrapper.addHeaderView(headView);

        recycleView.setAdapter(headerAndFooterWrapper);

        if (StringUtils.isEmpty(username)) {
            status = Status.NOT_LOGIN;
            name.setText("点击登录！");
            tipLayout.setVisibility(View.GONE);
            valueLayout.setVisibility(View.GONE);
            headIcon.setImageResource(R.drawable.comment_head_default);
        } else {
            if (volId == 0) {
                status = Status.NOT_VOL;
                tipLayout.setVisibility(View.GONE);
                valueLayout.setVisibility(View.GONE);
                name.setText("点击成为志愿者！");
                headIcon.setImageResource(R.drawable.comment_head_default);
            } else if (volId == -1) {
                status = Status.VOL_JUDGE;
                tipLayout.setVisibility(View.GONE);
                valueLayout.setVisibility(View.GONE);
                name.setText("您的志愿者资格审核中！");
                headIcon.setImageResource(R.drawable.comment_head_default);
            } else {
                status = Status.NORMAL;
                mPresenter.getDetail(volId + "");
            }
        }

        mPresenter.getList(page + "", type);

    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getList(page + "", type);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getList(page + "", type);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(page + "", type);
            }
        });

        headIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status) {
                    case NOT_LOGIN:
                        RouterManager.routerLogin(PracticeScoreRankActivity.this, 0);
                        break;
                    case NOT_VOL:

                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isVolunteer", true);
                        bundle.putString("instId",instId);
                        RouterManager.router(ARouterPathConstant.PRACTICE_VOLUNTEER_SIGN, bundle);
                        break;
                    case VOL_JUDGE:
                        showToast("您的志愿者资格审核中！");
                        break;
                    case ERROR:
                        showLoading();
                        mPresenter.getDetail(volId + "");
                        break;
                    case ERROR1:
                        mPresenter.getIsVolunteer(username);
                        break;
                }
            }
        });
    }

    @OnClick({R2.id.back_btn})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.back_btn) {
            finish();
        }
    }


    @Override
    public void setList(List<PracticeVolunteerBean> beanList, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Success);
        page++;
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        mDataList.addAll(beanList);
        headerAndFooterWrapper.notifyDataSetChanged();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(PracticeVolunteerDetailBean bean) {
        dismissLoading();
        if (bean != null) {
            Glide.with(this)
                    .load(bean.getLogo())
                    .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default))
                    .into(headIcon);

            name.setText(bean.getName());

            switch (type) {
                case 1:
                    rankNum.setText(StringUtils.isNotEmpty(bean.getRankingByTime())?bean.getRankingByTime():"100+");
                    break;
                case 2:
                    rankNum.setText(StringUtils.isNotEmpty(bean.getRankingByActNum())?bean.getRankingByActNum():"100+");
                    break;
                case 3:
                    rankNum.setText(StringUtils.isNotEmpty(bean.getRanking())?bean.getRanking():"100+");
                    break;
            }

            actNum.setText(bean.getServiceNums() + "");

            actTime.setText(DateUtils.PracticeServiceTimeFormat(bean.getServiceTimes()));

            scoreNum.setText(bean.getTotalScore() + "");

            tipLayout.setVisibility(View.VISIBLE);
            valueLayout.setVisibility(View.VISIBLE);
        } else {
            status = Status.ERROR;
            tipLayout.setVisibility(View.GONE);
            valueLayout.setVisibility(View.GONE);
            name.setText("获取志愿者信息失败，点击头像重试！");
            headIcon.setImageResource(R.drawable.comment_head_default);
        }
    }

    @Override
    public void setIsVolunteer(PracticeIsVolunteerBean bean) {
        if (bean != null) {
            volId = bean.getVolId();
            if (volId == 0) {
                status = Status.NOT_VOL;
                name.setText("点击成为志愿者！");
                tipLayout.setVisibility(View.GONE);
                valueLayout.setVisibility(View.GONE);
                headIcon.setImageResource(R.drawable.comment_head_default);
            } else {
                switch (bean.getStatus()) {
                    case "PASS":
                        status = Status.NORMAL;
                        mPresenter.getDetail(volId + "");
                        break;
                    case "NOT_VERIFY":
                        status = Status.VOL_JUDGE;
                        name.setText("您的志愿者资格审核中！");
                        tipLayout.setVisibility(View.GONE);
                        valueLayout.setVisibility(View.GONE);
                        headIcon.setImageResource(R.drawable.comment_head_default);
                        break;
                    default:
                        status = Status.NOT_VOL;
                        name.setText("点击成为志愿者！");
                        tipLayout.setVisibility(View.GONE);
                        valueLayout.setVisibility(View.GONE);
                        headIcon.setImageResource(R.drawable.comment_head_default);
                        break;
                }
            }
        } else {
            status = Status.ERROR1;
            name.setText("获取志愿者信息失败，点击头像重试！");
            headIcon.setImageResource(R.drawable.comment_head_default);
        }
    }

    @Override
    public void setError(String msg, boolean isMore) {
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {
                status = Status.VOL_JUDGE;
                username = CommonUtils.getInstance().getUserName();
                mPresenter.getIsVolunteer(username);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.PracticeActRefresh event) {
        if (event != null) {
            status = Status.VOL_JUDGE;
            name.setText("您的志愿者资格审核中！");
            headIcon.setImageResource(R.drawable.comment_head_default);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_RANK_SCORE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_RANK_SCORE);
    }

}
